<template>
    <div>
        <!--面包屑导航栏区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--卡片区域-->
        <el-card>
            <div style="margin-top: 15px;">
                <!--搜索框区域-->
                <el-row :gutter="20">
                <el-col :span="7"><el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList"><el-button slot="append" icon="el-icon-search" type='info' @click="getUserList"></el-button></el-input></el-col>
                <el-col :span="4"><el-button type="primary" @click="dialogVisible = true">添加用户</el-button></el-col>
                </el-row>
                <!--用户列表区域-->
                 <el-table :data="userList" style="width: 100%" border stripe>
                    <el-table-column  type="index" label="排序"></el-table-column>
                    <el-table-column  prop="username" label="姓名"></el-table-column>
                    <el-table-column prop="email" label="邮箱"></el-table-column>
                    <el-table-column prop="mobile" label="电话"></el-table-column>
                    <el-table-column prop="role_name" label="角色"></el-table-column>
                    <el-table-column prop="mg_state" label="状态">
                        <!--使用作用域插槽-->
                        <template slot-scope='scope'>
                            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200px">
                        <template slot-scope='scope'>
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeUser(scope.row.id)"></el-button>
                        <el-tooltip effect="dark" content="分配角色" placement="top-start" :enterable='false'>
                             <el-button size="mini" type="warning" icon="el-icon-setting" @click="showAssignDialog(scope.row)"></el-button>
                        </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
                <!--分页区域-->
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum"
                    :page-sizes="[1, 2, 5, 10]"
                    :page-size="queryInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </div>
        </el-card>
        <!--添加用户信息对话框-->
        <el-dialog
            title="添加用户"
            :visible.sync="dialogVisible"
            width="50%"
            @close="addDialogClosed">
            <!--验证表单-->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
            <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!--添加修改用户信息对话框-->
        <el-dialog
            title="修改用户"
            :visible.sync="EditDialogVisible"
            width="50%"
            @close="editDialogClosed">
            <!--验证表单-->
            <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
            <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="EditDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>
        <!--添加分配角色对话框-->
        <el-dialog
            title="分配角色"
            :visible.sync="assignDialogVisible"
            width="50%">
            <div>
                <p>用户名称 : {{userInfo.username}}</p>
                <p>角色名称 : {{userInfo.role_name}}</p>
                <!--角色多选框-->
                <el-select v-model="value" placeholder="请选择">
                    <el-option
                        v-for="item in rolesList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                    </el-option>
                </el-select>
            </div>
            <span slot="footer" class="dialog-footer">
            <el-button @click="assignDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="assignRoles">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data () {
             // 自定义验证规则
                var checkEmail = (rule, value, callback) => {
                // 验证邮箱的正则表达式
                const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
                if (regEmail.test(value)) return callback()
                callback(new Error('请输入合法的邮箱'))
       }
                // 自定义验证规则
                var checkMobile = (rule, value, callback) => {
                // 验证邮箱的正则表达式
                const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
                if (regMobile.test(value)) return callback()
                callback(new Error('请输入合法的手机号'))
       }
       return {
                queryInfo: {
                query: '',
                pagenum: 1,
                pagesize: 10
            },
            total: 0,
            userList: [],
            // 控制添加用户对话框的显示与隐藏
            dialogVisible: false,
            EditDialogVisible: false,
            addForm: {
                username: '',
                password: '',
                email: '',
                mobile: ''
            },
            addFormRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在3到10个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在6到15个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ]
            },
            editForm: {},
            userInfo: {},
            assignDialogVisible: false,
            rolesList: [],
            value: ''
       }
    },
    created () {
        this.getUserList()
    },
    methods: {
        // 获取用户列表
        async getUserList () {
            const { data: res } = await this.$http.get('users', { params: this.queryInfo })
            if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
            this.total = res.data.total
            this.userList = res.data.users
        },
        // 监听用户列表的显示条数
        handleSizeChange (newSize) {
            this.queryInfo.pagesize = newSize
            this.getUserList()
        },
        // 监听用户列表的当前页数
        handleCurrentChange (newPage) {
            this.queryInfo.pagenum = newPage
            this.getUserList()
        },
        // 监听Switch开关的状态
        async userStateChange (userInfo) {
            const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
            if (res.meta.status !== 200) {
                userInfo.mg_state = !userInfo.mg_state
                return this.$message.error('用户状态更新失败')
            }
            this.$message.success('用户状态更新成功')
        },
        addDialogClosed () {
        this.$refs.addFormRef.resetFields()
        },
        // 添加用户信息对话框
        addUser () {
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.post('users', this.addForm)
                if (res.meta.status !== 201) return this.$message.error('添加用户失败')
                this.$message.success('添加用户成功')
                this.dialogVisible = false
                this.getUserList()
            })
        },
        // 添加修改用户信息对话框
        // 通过template插槽scope.row传值id
        async showEditDialog (id) {
            this.EditDialogVisible = true
            const { data: res } = await this.$http.get('users/' + id)
            if (res.meta.status !== 200) return this.$message.error('查询用户信息失败')
            this.editForm = res.data
        },
        // 编辑用户对话框关闭后重置验证状态
        editDialogClosed () {
            this.$refs.editFormRef.resetFields()
        },
        // 提交修改后的用户信息
        editUser () {
            this.$refs.editFormRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.put('users/' + this.editForm.id, this.editForm)
                if (res.meta.status !== 200) return this.$message.error('修改用户信息失败')
                this.$message.success('修改用户信息成功')
                this.EditDialogVisible = false
                this.getUserList()
            })
        },
        // 删除用户信息
        async removeUser (id) {
            const result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).catch(err => err)
            // 用户确认删除，返回'confirm'，用户取消删除，返回'cancel'
            if (result !== 'confirm') return this.$message.info('取消删除用户信息')
            const { data: res } = await this.$http.delete('users/' + id)
            if (res.meta.status !== 200) return this.$message.error('删除用户信息失败')
            this.$message.success('删除用户信息成功')
            this.getUserList()
        },
        // 打开分配角色对话框
        async showAssignDialog (row) {
            this.userInfo = row
            this.assignDialogVisible = true
            // 获取所有角色列表
            const { data: res } = await this.$http.get('roles')
            if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
            this.rolesList = res.data
        },
        // 提交重新分配的角色
        async assignRoles () {
            const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
                rid: this.value
            })
            if (res.meta.status !== 200) return this.$message.error('提交分配角色失败')
            this.$message.success('提交角色成功')
            this.getUserList()
            this.assignDialogVisible = false
        }
    }
}
</script>
<style lang="less" scoped>

</style>
